<template>
  <a-modal
    v-model:open="visible"
    title="选择角色"
    :width="600"
    :loading="loading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    ok-text="提交"
    cancel-text="取消"
  >
    <div class="role-selection">
      <!-- 搜索框 -->
      <div class="search-section">
        <a-input
          v-model:value="searchKeyword"
          placeholder="搜索角色名称或描述..."
          allow-clear
          class="search-input"
        >
          <template #prefix>
            <SearchOutlined />
          </template>
        </a-input>
      </div>

      <!-- 选择提示 -->
      <div class="selection-info">
        <span class="selected-count">已选择 {{ selectedRoles.length }}/5 个角色</span>
        <span v-if="selectedRoles.length >= 5" class="limit-warning">最多只能选择5个角色</span>
      </div>

      <!-- 角色列表 -->
      <div class="role-list">
        <div v-if="loading && allRoles.length === 0" class="loading-state">
          <a-spin size="large" />
          <div class="loading-text">加载角色列表中...</div>
        </div>

        <div v-else-if="filteredRoles.length === 0" class="empty-state">
          <div class="empty-icon">🤖</div>
          <div class="empty-text">{{ searchKeyword ? '未找到匹配的角色' : '暂无可用角色' }}</div>
        </div>

        <div v-else class="role-grid">
          <div
            v-for="role in filteredRoles"
            :key="role.id"
            class="role-card"
            :class="{
              'role-selected': isRoleSelected(role.id),
              'role-disabled': !isRoleSelected(role.id) && selectedRoles.length >= 5
            }"
            @click="toggleRoleSelection(role)"
          >
            <div class="role-checkbox">
              <a-checkbox
                :checked="isRoleSelected(role.id)"
                :disabled="!isRoleSelected(role.id) && selectedRoles.length >= 5"
                @click.stop
                @change="(e: any) => handleCheckboxChange(role.id, e)"
              />
            </div>

            <div class="role-avatar">
              <a-avatar
                :size="48"
                :src="role.avatarUrl"
                :style="role.avatarUrl ? {} : { backgroundColor: getRoleColor(role.id), color: 'white' }"
              >
                {{ (role.roleName || '角色')[0]?.toUpperCase() || 'R' }}
              </a-avatar>
            </div>

            <div class="role-info">
              <div class="role-name">{{ role.roleName }}</div>
              <div class="role-description">{{ role.prompt || '暂无描述' }}</div>
            </div>

            <!-- 已在聊天室标识 -->
            <div v-if="isRoleInChatRoom(role.id)" class="in-room-badge">
              已在聊天室
            </div>
          </div>
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { message } from 'ant-design-vue'
import { SearchOutlined } from '@ant-design/icons-vue'
import { Codewin } from '@/api/generated/Codewin'
import { roleService } from '@/api/roleService'
import type { ChatRoomRoleVO } from '@/api/generated/data-contracts'
import type { ExtendedRole } from '@/api/roleService'
import { useAuthStore } from '@/stores'

interface Props {
  open: boolean
  roomId?: string
}

interface Emits {
  (e: 'update:open', value: boolean): void
  (e: 'submit', roleIds: string[]): void
}

const props = withDefaults(defineProps<Props>(), {
  roomId: ''
})

const emit = defineEmits<Emits>()

// 响应式状态
const visible = ref(false)
const loading = ref(false)
const searchKeyword = ref('')
const allRoles = ref<ExtendedRole[]>([])
const chatRoomRoles = ref<ChatRoomRoleVO[]>([])
const selectedRoles = ref<string[]>([])

// 获取认证store
const authStore = useAuthStore()

// 创建API实例
const api = new Codewin({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  securityWorker: (securityData) => {
    const token = authStore.token
    return token ? { headers: { Authorization: `Bearer ${token}` } } : {}
  }
})

// 监听 props.open 变化
watch(() => props.open, async (newVal) => {
  visible.value = newVal
  if (newVal) {
    await Promise.all([
      fetchAllRoles(),
      props.roomId ? fetchChatRoomRoles() : Promise.resolve()
    ])
  }
})

// 监听 visible 变化
watch(visible, (newVal) => {
  emit('update:open', newVal)
  if (!newVal) {
    // 重置状态
    searchKeyword.value = ''
    selectedRoles.value = []
  }
})

// 过滤后的角色列表
const filteredRoles = computed(() => {
  let filtered = allRoles.value

  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(role =>
      (role.roleName || '').toLowerCase().includes(keyword) ||
      (role.prompt || '').toLowerCase().includes(keyword)
    )
  }

  return filtered
})

// 获取所有角色列表
const fetchAllRoles = async () => {
  loading.value = true
  try {
    // 获取用户角色
    const userRolesResponse = await roleService.getRoleList({
      pageNo: 1,
      pageSize: 100
    })

    // 获取默认角色
    const defaultRolesResponse = await roleService.getDefaultRoles({
      pageNo: 1,
      pageSize: 100
    })

    // 合并角色列表并通过id去重
    const userRoles = userRolesResponse.records
    const defaultRoles = defaultRolesResponse.records

    // 创建一个Map来存储唯一的角色，以id为key
    const roleMap = new Map()

    // 先添加用户角色（优先级更高）
    userRoles.forEach(role => {
      if (role.id) {
        roleMap.set(role.id, role)
      }
    })

    // 再添加默认角色，如果id已存在则跳过
    defaultRoles.forEach(role => {
      if (role.id && !roleMap.has(role.id)) {
        roleMap.set(role.id, role)
      }
    })

    // 转换为数组
    allRoles.value = Array.from(roleMap.values())
    console.log(allRoles.value)
  } catch (error) {
    console.error('获取角色列表失败:', error)
    message.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 获取聊天室已绑定的角色
const fetchChatRoomRoles = async () => {
  if (!props.roomId) return

  try {
    const response = await api.getChatRoomRoles(props.roomId)
    if (response.data?.code === 0 && response.data?.data) {
      chatRoomRoles.value = response.data.data
      // 设置已在聊天室的角色为默认选中
      selectedRoles.value = chatRoomRoles.value
        .map(role => role.id)
        .filter((id): id is string => !!id)
    }
  } catch (error) {
    console.error('获取聊天室角色失败:', error)
  }
}

// 判断角色是否已选中
const isRoleSelected = (roleId?: string) => {
  return roleId ? selectedRoles.value.includes(roleId) : false
}

// 判断角色是否已在聊天室中
const isRoleInChatRoom = (roleId?: string) => {
  return roleId ? chatRoomRoles.value.some(role => role.id === roleId) : false
}

// 切换角色选择状态
const toggleRoleSelection = (role: ExtendedRole) => {
  if (!role.id) return

  const isSelected = isRoleSelected(role.id)

  if (isSelected) {
    // 取消选择
    selectedRoles.value = selectedRoles.value.filter(id => id !== role.id)
  } else {
    // 选择角色
    if (selectedRoles.value.length >= 5) {
      message.warning('最多只能选择5个角色')
      return
    }
    selectedRoles.value.push(role.id)
  }
}

// 处理复选框变化
const handleCheckboxChange = (roleId: string, e: any) => {
  const target = e.target as HTMLInputElement
  if (target.checked) {
    if (selectedRoles.value.length >= 5) {
      message.warning('最多只能选择5个角色')
      return
    }
    if (roleId && !selectedRoles.value.includes(roleId)) {
      selectedRoles.value.push(roleId)
    }
  } else {
    if (roleId) {
      selectedRoles.value = selectedRoles.value.filter(id => id !== roleId)
    }
  }
}

// 获取角色颜色
const getRoleColor = (roleId?: string) => {
  const colors = [
    '#6366f1', '#8b5cf6', '#ec4899', '#ef4444',
    '#f59e0b', '#10b981', '#06b6d4', '#3b82f6'
  ]
  if (!roleId) return colors[0]
  const index = roleId.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0)
  return colors[index % colors.length]
}

// 处理提交
const handleSubmit = () => {
  emit('submit', selectedRoles.value)
  visible.value = false
}

// 处理取消
const handleCancel = () => {
  visible.value = false
}
</script>

<style scoped>
.role-selection {
  padding: 8px 0;
}

.search-section {
  margin-bottom: 16px;
}

.search-input {
  width: 100%;
}

.selection-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 8px 12px;
  background: #f5f5f5;
  border-radius: 6px;
  font-size: 14px;
}

.selected-count {
  color: #666;
  font-weight: 500;
}

.limit-warning {
  color: #ff4d4f;
  font-size: 12px;
}

.role-list {
  max-height: 400px;
  overflow-y: auto;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  color: #666;
}

.loading-text {
  margin-top: 12px;
  font-size: 14px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  color: #999;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 12px;
}

.empty-text {
  font-size: 14px;
}

.role-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 12px;
}

.role-card {
  position: relative;
  display: flex;
  align-items: center;
  padding: 12px;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  background: #fff;
}

.role-card:hover {
  border-color: #6366f1;
  box-shadow: 0 2px 8px rgba(99, 102, 241, 0.1);
}

.role-card.role-selected {
  border-color: #6366f1;
  background: #f0f0ff;
}

.role-card.role-disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.role-card.role-disabled:hover {
  border-color: #e8e8e8;
  box-shadow: none;
}

.role-checkbox {
  margin-right: 12px;
}

.role-avatar {
  margin-right: 12px;
  flex-shrink: 0;
}

.role-info {
  flex: 1;
  min-width: 0;
}

.role-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.role-description {
  font-size: 12px;
  color: #666;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.in-room-badge {
  position: absolute;
  top: 4px;
  right: 4px;
  background: #52c41a;
  color: white;
  font-size: 10px;
  padding: 2px 6px;
  border-radius: 10px;
  white-space: nowrap;
}

/* 滚动条样式 */
.role-list::-webkit-scrollbar {
  width: 6px;
}

.role-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.role-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.role-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
